from mcp.server.fastmcp import FastMCP, Context
import subprocess
import json
from typing import List

mcp = FastMCP("Initscripts MCP Server")

"""
面向软件：initscripts（系统初始化脚本）
所有 MCP tool 列表：

1. import_state_service_control
   - 用途：测试 import-state.service 的执行和一次性服务功能
   - 参数：无
   - 返回：统一 JSON 结构

2. loadmodules_service_control  
   - 用途：测试 loadmodules.service 的执行和重载功能
   - 参数：无
   - 返回：统一 JSON 结构

3. netconsole_service_control
   - 用途：测试 netconsole.service 的执行和重载功能
   - 参数：无
   - 返回：统一 JSON 结构

4. network_service_control
   - 用途：测试 network.service 的重启、状态检查和日志查询功能
   - 参数：无
   - 返回：统一 JSON 结构

5. readonly_root_service_control
   - 用途：测试 readonly-root.service 的执行、启动和重载检查功能
   - 参数：无
   - 返回：统一 JSON 结构
"""

@mcp.tool()
def import_state_service_control() -> dict:
    """
    测试 import-state.service 的执行和一次性服务功能
    
    返回 JSON 结构：
    {
        "success": bool,      # 操作是否成功
        "command": str,       # 执行的命令
        "exit_code": int,     # 退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    try:
        # 测试服务执行
        result1 = subprocess.run(["systemctl", "status", "import-state.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 测试一次性服务
        result2 = subprocess.run(["systemctl", "is-active", "import-state.service"], 
                               capture_output=True, text=True, timeout=30)
        
        return {
            "success": result1.returncode == 0 or result2.returncode == 0,
            "command": "systemctl status import-state.service && systemctl is-active import-state.service",
            "exit_code": result1.returncode if result1.returncode != 0 else result2.returncode,
            "stdout": f"Status: {result1.stdout}\nIs-active: {result2.stdout}",
            "stderr": f"Status: {result1.stderr}\nIs-active: {result2.stderr}"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "import-state.service control",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def loadmodules_service_control() -> dict:
    """
    测试 loadmodules.service 的执行和重载功能
    
    返回 JSON 结构：
    {
        "success": bool,      # 操作是否成功
        "command": str,       # 执行的命令
        "exit_code": int,     # 退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    try:
        # 测试服务执行
        result1 = subprocess.run(["systemctl", "status", "loadmodules.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 测试服务重载
        result2 = subprocess.run(["systemctl", "reload", "loadmodules.service"], 
                               capture_output=True, text=True, timeout=30)
        
        return {
            "success": result1.returncode == 0 or result2.returncode == 0,
            "command": "systemctl status loadmodules.service && systemctl reload loadmodules.service",
            "exit_code": result1.returncode if result1.returncode != 0 else result2.returncode,
            "stdout": f"Status: {result1.stdout}\nReload: {result2.stdout}",
            "stderr": f"Status: {result1.stderr}\nReload: {result2.stderr}"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "loadmodules.service control",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def netconsole_service_control() -> dict:
    """
    测试 netconsole.service 的执行和重载功能
    
    返回 JSON 结构：
    {
        "success": bool,      # 操作是否成功
        "command": str,       # 执行的命令
        "exit_code": int,     # 退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    try:
        # 测试服务执行
        result1 = subprocess.run(["systemctl", "status", "netconsole.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 测试服务重载
        result2 = subprocess.run(["systemctl", "reload", "netconsole.service"], 
                               capture_output=True, text=True, timeout=30)
        
        return {
            "success": result1.returncode == 0 or result2.returncode == 0,
            "command": "systemctl status netconsole.service && systemctl reload netconsole.service",
            "exit_code": result1.returncode if result1.returncode != 0 else result2.returncode,
            "stdout": f"Status: {result1.stdout}\nReload: {result2.stdout}",
            "stderr": f"Status: {result1.stderr}\nReload: {result2.stderr}"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "netconsole.service control",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def network_service_control() -> dict:
    """
    测试 network.service 的重启、状态检查和日志查询功能
    
    返回 JSON 结构：
    {
        "success": bool,      # 操作是否成功
        "command": str,       # 执行的命令
        "exit_code": int,     # 退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    try:
        # 重启服务
        result1 = subprocess.run(["systemctl", "restart", "network.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 检查服务状态
        result2 = subprocess.run(["systemctl", "status", "network.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 检查日志错误
        result3 = subprocess.run(["journalctl", "-u", "network.service", "--since", "1 hour ago"], 
                               capture_output=True, text=True, timeout=30)
        
        # 测试重载（应该不适用）
        result4 = subprocess.run(["systemctl", "reload", "network.service"], 
                               capture_output=True, text=True, timeout=30)
        
        return {
            "success": result1.returncode == 0 and "Active: active" in result2.stdout,
            "command": "systemctl restart network.service && systemctl status network.service && journalctl -u network.service --since '1 hour ago' && systemctl reload network.service",
            "exit_code": result1.returncode if result1.returncode != 0 else result2.returncode,
            "stdout": f"Restart: {result1.stdout}\nStatus: {result2.stdout}\nJournal: {result3.stdout}\nReload: {result4.stdout}",
            "stderr": f"Restart: {result1.stderr}\nStatus: {result2.stderr}\nJournal: {result3.stderr}\nReload: {result4.stderr}"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "network.service control",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

@mcp.tool()
def readonly_root_service_control() -> dict:
    """
    测试 readonly-root.service 的执行、启动和重载检查功能
    
    返回 JSON 结构：
    {
        "success": bool,      # 操作是否成功
        "command": str,       # 执行的命令
        "exit_code": int,     # 退出码
        "stdout": str,        # 标准输出
        "stderr": str         # 标准错误
    }
    """
    try:
        # 测试服务执行
        result1 = subprocess.run(["systemctl", "status", "readonly-root.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 启动服务
        result2 = subprocess.run(["systemctl", "start", "readonly-root.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 测试重载（应该不适用）
        result3 = subprocess.run(["systemctl", "reload", "readonly-root.service"], 
                               capture_output=True, text=True, timeout=30)
        
        # 检查服务状态
        result4 = subprocess.run(["systemctl", "status", "readonly-root.service"], 
                               capture_output=True, text=True, timeout=30)
        
        return {
            "success": result2.returncode == 0 and "Job type reload is not applicable" in result3.stderr,
            "command": "systemctl status readonly-root.service && systemctl start readonly-root.service && systemctl reload readonly-root.service && systemctl status readonly-root.service",
            "exit_code": result2.returncode if result2.returncode != 0 else result3.returncode,
            "stdout": f"Status1: {result1.stdout}\nStart: {result2.stdout}\nReload: {result3.stdout}\nStatus2: {result4.stdout}",
            "stderr": f"Status1: {result1.stderr}\nStart: {result2.stderr}\nReload: {result3.stderr}\nStatus2: {result4.stderr}"
        }
    except Exception as e:
        return {
            "success": False,
            "command": "readonly-root.service control",
            "exit_code": -1,
            "stdout": "",
            "stderr": str(e)
        }

if __name__ == "__main__":
    mcp.run()